package cn.lili.modules.goods_auth.manage;

import cn.hutool.core.lang.Assert;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.RSAPCIUtil;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.client.GoodsSkuClient;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods_auth.service.AuthSpaceGoodsService;
import cn.lili.modules.system.entity.dos.GoodsAuthOpen;
import cn.lili.modules.system.entity.dos.LiAuth;
import cn.lili.modules.system.entity.dos.LiAuthSpaceGoods;
import cn.lili.modules.system.entity.dto.SpaceGoodsSearchParams;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品授权扩展
 * @author xiangqian
 * @version 1.0
 * @data 2023/11/28 10:46
 */
@Component
public class GoodsAuthManage {

    @Resource
    private AuthSpaceGoodsService authSpaceGoodsService;
    @Resource
    private GoodsClient goodsClient;
    @Resource
    private GoodsSkuClient goodsSkuClient;

    /**
     * 验证签名
     *
     * @param sign           签名字符串
     * @param liAuth         授权配置
     * @param goodsAuthOpen  拉取商品请求参数
     * @throws Exception     验证失败时抛出异常
     */
    public void verifySignature(String sign, LiAuth liAuth, GoodsAuthOpen goodsAuthOpen) throws Exception {
        byte[] signBytes = RSAPCIUtil.hex2Byte(sign);
        PrivateKey privateKey = RSAPCIUtil.getPrivateKey(liAuth.getPrivateKey());
        byte[] decryptedBytes = RSAPCIUtil.decrypt(signBytes, privateKey);

        // 校验参数
        String expectedString = goodsAuthOpen.getPageNumber() +
                goodsAuthOpen.getPageSize() +
                goodsAuthOpen.getAppid() +
                goodsAuthOpen.getAuth() +
                goodsAuthOpen.getSpaceCode();
        Assert.isTrue(Objects.equals(new String(decryptedBytes), expectedString), "校验失败");
    }

    /**
     * 根据空间编号获取商品分页数据
     *
     * @param spaceCode    空间编号
     * @param pageNumber  页码
     * @param pageSize    每页大小
     * @return 商品分页数据
     */
    public Page<Goods> getGoodsPageBySpaceCode(String spaceCode, int pageNumber, int pageSize) {
        SpaceGoodsSearchParams searchParams = new SpaceGoodsSearchParams();
        searchParams.setAuthSpaceCode(spaceCode);
        searchParams.setPageNumber(pageNumber);
        searchParams.setPageSize(pageSize);
        Page<LiAuthSpaceGoods> liAuthSpaceGoodsPage = authSpaceGoodsService.spaceGoods(searchParams);

        // 查询具体商品数据
        if (!liAuthSpaceGoodsPage.getRecords().isEmpty()) {
            List<String> goodsIds = liAuthSpaceGoodsPage.getRecords().stream().map(LiAuthSpaceGoods::getGoodsId).toList();
            GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
            goodsSearchParams.setIds(goodsIds);
            goodsSearchParams.setAuthFlag(GoodsAuthEnum.PASS.name());
            goodsSearchParams.setMarketEnable(GoodsMarketEnum.UPPER.name());
            goodsSearchParams.setScene(SceneEnums.STORE.name());
            Page<Goods> page = goodsClient.queryByParams(goodsSearchParams);

            //重置page.getRecords()
            List<Goods> resultGoods = new ArrayList<>();
            page.getRecords().forEach(e->{
                List<GoodsSku> list = goodsSkuClient.getGoodsSkuByGoodsIdList(Collections.singletonList(e.getId()));
                if(list != null && !list.isEmpty()){
                    GoodsSku goodsSku = list.stream().sorted(Comparator.comparing(GoodsSku::getPrice)).toList().get(0);
                    e.setCommentNum((goodsSku.getCommentNum() != null ? goodsSku.getCommentNum() : 0) + (goodsSku.getVirtualEvaluateCount() != null ? goodsSku.getVirtualEvaluateCount() : 0));
                    e.setBuyCount((goodsSku.getBuyCount() != null ? goodsSku.getBuyCount() : 0) + (goodsSku.getVirtualBuyCount() != null ? goodsSku.getVirtualBuyCount() : 0));
                }
                resultGoods.add(e);
            });
            page.setRecords(resultGoods);

            //排序
            sortPage(goodsIds,page);
            page.setTotal(liAuthSpaceGoodsPage.getTotal());
            return page;
        } else {
            return null;
        }
    }

    /**
     * 排序
     * */
    public Page<Goods> sortPage (List<String> goodsIds,Page<Goods> page){
        page.setRecords(page.getRecords().stream()
                .sorted(Comparator.comparing(g -> goodsIds.indexOf(g.getId())))
                .collect(Collectors.toList()));
        return page;
    }
}
